package Controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.torque.NoRowsException;
import org.apache.torque.TooManyRowsException;
import org.apache.torque.TorqueException;

import Models.Groupe;
import Models.GroupePeer;
import Models.Module;
import Models.ModulePeer;

@SuppressWarnings("serial")
public class ModulesController extends MainController {
	private String addView, listView, viewView, errorView, editView;
	// INIT
	public void init() throws ServletException {
		this.addView 	= this.getInitParameter("view_add");
		this.listView	= this.getInitParameter("view_list");
		this.viewView	= this.getInitParameter("view_view");
		this.errorView	= this.getInitParameter("view_error");
		this.editView	= this.getInitParameter("view_edit");
	}
	
	// POST
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String method = request.getMethod().toLowerCase();
		String action = request.getPathInfo();
		if (action == null) {
			action = "/";
			System.out.println("action == null");
		}
		if (method.equals("post") && action.equals("/add")) {
			request.setAttribute("title", "Ajouter un module");
			this.add(request, response);
		} else if (method.equals("post") && action.equals("/edit")) {
			this.edit(request, response);
		}
	}

	// GET
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		// On récupère la méthode d'envoi de la requête
		String method = request.getMethod().toLowerCase();
		
		// On récupère l'action à exécuter
		String action = request.getPathInfo();
		if (action == null) {
			action = "/";
			System.out.println("action == null");
		}
		
		if (method.equals("get") && action.equals("/add")) {
			request.setAttribute("title", "Ajouter un module");
			this.add(request, response);
		} else if (method.equals("get") && action.equals("/edit")) {
			this.add(request, response);
		} else if (method.equals("get") && action.equals("/list")) {
			request.setAttribute("title", "Liste des modules");
			this.list(request, response);
		} else if (method.equals("get") && action.equals("/view")) {
			this.view(request, response);
		}
	}
	
	private void view(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Module m = ModulePeer.retrieveByPK(Integer.parseInt(request.getParameter("m")));
			request.setAttribute("mod", m);
			request.setAttribute("title", "Module "+m.getNom());
			this.loadJSP(this.viewView, request, response);
		} catch (NoRowsException e) {
			request.setAttribute("message", "Ce module n'existe pas");
			request.setAttribute("title", "Erreur");
			request.setAttribute("title_error", "Aucun module");
			this.loadJSP(this.errorView, request, response);
		} catch (TooManyRowsException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			request.setAttribute("message", "Ce module n'existe pas");
			request.setAttribute("title", "Erreur");
			request.setAttribute("title_error", "Aucun module");
			this.loadJSP(this.errorView, request, response);
		} catch (TorqueException e) {
			e.printStackTrace();
		}
	}

	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Module> mods = ModulePeer.doSelectAll();
		request.setAttribute("mods", mods);
		this.loadJSP(this.listView, request, response);
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request.getParameter("add") != null) {
			boolean err = false;
			if (request.getParameter("nom").isEmpty()) {
				request.setAttribute("err-nom", "Le nom du module doit être renseigné");
				err = true;
			}
			if (request.getParameter("description").isEmpty()) {
				request.setAttribute("err-desc", "La description du module doit être renseignée");
				err = true;
			}
			if (request.getParameterMap().size() <= 3) {
				request.setAttribute("err-grp", "Le module doit être associé à au moins un groupe");
				err = true;
			}
			Module newm = new Module(request.getParameter("nom"), request.getParameter("description"));
			List<Module> mods = ModulePeer.doSelectByNom(request.getParameter("nom"));
			if (mods.size() != 0) {
				request.setAttribute("err-nom", "Le nom de ce module est déjà utilisé");
					err = true;
			}
			if (!err) {
				List<Integer> g = new ArrayList<Integer>();
				for (String p : request.getParameterMap().keySet()) {
					if (p.length() > 6 && p.substring(0, 6).equals("groupe")) {
						g.add(Integer.parseInt(request.getParameter(p)));
					}
				}
				ModulePeer.doInsert(newm, g);
				request.setAttribute("saved", "Le module <strong>"+newm.getNom()+"</strong> a bien été enregistré");
			}
		}
		request.setAttribute("g", (List<Groupe>) GroupePeer.doSelectAll());
		this.loadJSP(this.addView, request, response);
	}
	
	private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Module m = ModulePeer.retrieveByPK(Integer.parseInt(request.getParameter("m")));
			
			if (request.getParameter("add") != null) {
				boolean err = false;
				if (request.getParameter("nom").isEmpty()) {
					request.setAttribute("err-nom", "Le nom du module doit être renseigné");
					err = true;
				}
				if (request.getParameter("description").isEmpty()) {
					request.setAttribute("err-desc", "La description du module doit être renseignée");
					err = true;
				}
				if (request.getParameterMap().size() <= 3) {
					request.setAttribute("err-grp", "Le module doit être associé à au moins un groupe");
					err = true;
				}
				Module newm = new Module(request.getParameter("nom"), request.getParameter("description"));
				List<Module> mods = ModulePeer.doSelectByNom(request.getParameter("nom"));
				if (mods.size() != 0) {
					request.setAttribute("err-nom", "Le nom de ce module est déjà utilisé");
						err = true;
				}
				if (!err) {
					List<Integer> g = new ArrayList<Integer>();
					for (String p : request.getParameterMap().keySet()) {
						if (p.length() > 6 && p.substring(0, 6).equals("groupe")) {
							g.add(Integer.parseInt(request.getParameter(p)));
						}
					}
					ModulePeer.doUpdate(newm, g);
					request.setAttribute("saved", "Le module <strong>"+newm.getNom()+"</strong> a bien été enregistré");
				}
			}
			request.setAttribute("g", (List<Groupe>) GroupePeer.doSelectAll());
			request.setAttribute("mod", m);
			this.loadJSP(this.editView, request, response);
		} catch (NoRowsException e) {
			request.setAttribute("message", "Ce module n'existe pas");
			request.setAttribute("title", "Erreur");
			request.setAttribute("title_error", "Aucun module");
			this.loadJSP(this.errorView, request, response);
		} catch (TooManyRowsException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			request.setAttribute("message", "Ce module n'existe pas");
			request.setAttribute("title", "Erreur");
			request.setAttribute("title_error", "Aucun module");
			this.loadJSP(this.errorView, request, response);
		} catch (TorqueException e) {
			e.printStackTrace();
		}
	}
}
